<template>
	<div class="warpper">
		<van-submit-bar :price="money*100" button-text="提交订单" @submit="onSubmit" tip="向左滑动商品可删除该商品！">
			<van-checkbox v-model="value" @click="toggleAll(ckAll==false?true:false)">全选</van-checkbox>
		</van-submit-bar>
		<van-empty description="空空如也!" v-if="cartList.length<=0" />
		<div class="cart">
			<van-checkbox-group v-model="result" ref="checkboxGroup">
								<!-- 前提是不能为拼团商品或者积分商品 -->
				<van-swipe-cell v-for="item in cartList" :key="item.id"
				v-if="item.combinationId==0 && item.productInfo.isIntegral != 1">
					<van-card :num="item.cartNum" :desc="item.productInfo.storeInfo"
					:title="item.productInfo.storeName" :thumb="imgUrls+item.productInfo.image">
						<template #tags>
							<van-tag plain type="danger" style="margin-top: 10px;">{{item.productInfo.attrInfo.sku}}
							</van-tag>
						</template>
						<template #price>
							<span v-if="item.productInfo.isIntegral === 1">
								<font color="red" size ="3">{{parseInt(item.truePrice)}} 积分</font>
							</span>
							<span v-else-if="!item.combinationId">
								<font color="red" size="3"> ￥{{item.truePrice}}</font>
							</span>
							<span v-if="item.combinationId">
								<font color="red" size="3"> 拼团价：￥{{item.truePrice}}</font>
							</span>
						</template>
						<template #footer>
							<van-stepper v-model="item.cartNum" integer @change="onChange" :value="changevalue"
								@plus="itemId=item.id" @minus="itemId=item.id" @focus="itemId=item.id" />
						</template>
						<template #tag>
							<van-checkbox :name="item.id" @click="toggle(item.id,item.truePrice*item.cartNum)"
								checked-color="#ee0a24"></van-checkbox>
						</template>
					</van-card>
					<template #right>
						<van-button square text="删除" type="danger" class="delete-button" @click="del(item.id)" />
					</template>
				</van-swipe-cell>

			</van-checkbox-group>
		</div>
	</div>
</template>

<script>
	import {
		getCartList,
		upCartNum,
		delCart
	} from "@/api/cart.js"
	export default {
		data() {
			return {
				imgUrls: this.$baseApi,
				changevalue: 0, //计数器
				cartList: [],
				value: false, //控制全选按钮
				money: 0, //总金额
				result: [], //全选的 name数组
				list: [], //获取点击的id数组
				ckAll: false, //是否全选
				itemId: null, //商品id 改变商品数量时使用
			};
		},
		created() {
			this.getCart()
		},
		methods: {
			//获取购物车列表
			getCart() {
				getCartList().then(res => {
					this.cartList = res.data.valid
				})
			},
			//获取点击的name 复选框
			toggle(name, money) {
				for (let i = 0; i < this.list.length; i++) {
					// 取消复选框 则 减少价格
					if (this.list[i] == name) {
						this.ckAll = false
						this.money = this.money - money
						this.list.splice(i, 1);
						name = null
						this.value = false
						return
					}
				}
				// 否则添加价格
				if (name != null) {
					this.list.push(name)
					this.money = this.money + money
				}
			},
			updateMoney(){
				this.money = 0
				let vm = this;
				//这里list存的就是勾选上的商品id
				let ids = this.list.map(x=>x);
				//遍历原购物车数组，看哪些对应上了
				this.cartList.forEach(item=>{
					if(ids.indexOf(item.id) > -1){
						vm.money = vm.money + item.cartNum * item.truePrice;
					}
				})
			},
			//修改购物车数量 这个value是组件自动传过来的，所以在调用的时候不需要自己手动传参
			//这个value实际上就是修改后传过来的值
			onChange(value) {
				//这段代码很重要，必须要加上！！！
				//因为当你点击了加号或者减号按钮，就已经修改了cartList中对应商品的cartNum(v-model)
				//但是这种对象里面属性的更新是不会被检测到，也就是做响应式的
				//因此每次进来我们都需要重新计算一次价格，可能用watch深度监视也能达到效果，但是这样是最简单的
				this.updateMoney();
				//这里的异步变更在vant-ui文档中有
				this.$toast.loading({
					forbidClick: true
				});
				let vm = this
				clearTimeout(vm.timer);
				vm.timer = setTimeout(() => {
					vm.$toast.clear();
					vm.changevalue = value;
					if (vm.changevalue > 0 && vm.itemId != null) {
						upCartNum({
							number: vm.changevalue,
							id: vm.itemId
						}).then(res => {})
					}
				}, 500);
			},
			//提交按钮
			onSubmit() {
				//判断勾选的购物车商品数量是大于0还是小于0
				if (this.list.length > 0) {
					if (this.list.length == 1) {
						this.$router.push({
							name: 'CreationOrder',
							query: {
								ids: this.list[0]
							}
						});
					} else {
						this.$router.push({
							name: 'CreationOrder',
							query: {
								ids: JSON.stringify(this.list).replace('[', '').replace(']', '')
							}
						});
					}

				} else {
					this.$toast.fail("至少选择一件商品！")
				}


			},
			//删除
			del(id) {
				let list = []
				list.push(id)
				delCart({
					ids: list
				}).then(res => {
					if (res.status) {
						this.getCart()
						this.$toast.success('删除成功');
					}
				})
			},
			//全选
			toggleAll(ckAll) {
				this.money = 0
				this.$refs.checkboxGroup.toggleAll(ckAll);
				this.ckAll = ckAll
				this.list = []
				let money = 0
				if (ckAll) {
					//计算总金额
					this.cartList.forEach(item => {
						//如果该商品是积分支付的话就不管他
						if(item.productInfo.isIntegral === 1) return;
						//否则正常商品累加价格
						money = money + item.productInfo.attrInfo.price * item.cartNum
						this.list.push(item.id)
					})
					this.money = money
				} else {
					this.list = []
					this.money = money
				}
			},
		},
	};
</script>

<style scoped>
	.warpper {
		position: absolute;

		left: 0px;
		right: 0px;
		height: 80%;
		background: #fff;
	}

	.cart {

		background-color: #FFFFFF;
		padding: 10px;
	}

	.delete-button {
		height: 100%;
	}

	.van-swipe-cell {
		margin-top: 5px;
	}
</style>
